//
//  CustomSearchBar.swift
//  DKE-Album
//
//  Created by dagny on 2025/9/20.
//  Copyright © 2025 杨东宝. All rights reserved.
//

import Foundation
import UIKit

// 搜索框委托协议
protocol CustomSearchBarDelegate: AnyObject {
    func searchBar(_ searchBar: CustomSearchBar, textDidChange searchText: String)
    func searchBarSearchButtonClicked(_ searchBar: CustomSearchBar)
    func searchBarClearButtonClicked(_ searchBar: CustomSearchBar)
    func searchBarDidBeginEditing(_ searchBar: CustomSearchBar)
    func searchBarDidEndEditing(_ searchBar: CustomSearchBar)
}

// 提供默认空实现，使代理方法可选
extension CustomSearchBarDelegate {
    func searchBar(_ searchBar: CustomSearchBar, textDidChange searchText: String) {}
    func searchBarSearchButtonClicked(_ searchBar: CustomSearchBar) {}
    func searchBarClearButtonClicked(_ searchBar: CustomSearchBar) {}
    func searchBarDidBeginEditing(_ searchBar: CustomSearchBar) {}
    func searchBarDidEndEditing(_ searchBar: CustomSearchBar) {}
}

// 自定义搜索框
class CustomSearchBar: UIView {
    
    // MARK: - 公共属性
    weak var delegate: CustomSearchBarDelegate?
    
    var placeholder: String = "搜索" {
        didSet {
            textField.placeholder = placeholder
        }
    }
    
    var text: String {
        get { return textField.text ?? "" }
        set {
            textField.text = newValue
            updateClearButtonVisibility()
        }
    }
    
    var cornerRadius: CGFloat = 10 {
        didSet {
            layer.cornerRadius = cornerRadius
        }
    }
    
    var borderWidth: CGFloat = 1 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }
    
    var borderColor: UIColor = .lightGray {
        didSet {
            layer.borderColor = borderColor.cgColor
        }
    }
    
    var textColor: UIColor = .black {
        didSet {
            textField.textColor = textColor
        }
    }
    
    var placeholderColor: UIColor = .lightGray {
        didSet {
            if let placeholder = textField.placeholder {
                textField.attributedPlaceholder = NSAttributedString(
                    string: placeholder,
                    attributes: [NSAttributedString.Key.foregroundColor: placeholderColor]
                )
            }
        }
    }
    
    var searchIconColor: UIColor = .lightGray {
        didSet {
            searchIconView.tintColor = searchIconColor
        }
    }
    
    var clearButtonColor: UIColor = .lightGray {
        didSet {
            clearButton.tintColor = clearButtonColor
        }
    }
    
    // MARK: - 私有属性
    private let textField = UITextField()
    private let searchIconView = UIImageView()
    private let clearButton = UIButton()
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    // MARK: - 设置方法
    private func setupView() {
        // 设置视图外观
        backgroundColor = .white
        layer.cornerRadius = cornerRadius
        layer.borderWidth = borderWidth
        layer.borderColor = borderColor.cgColor
        
        // 设置搜索图标
        searchIconView.image = UIImage(named: "searchIcon")?.withRenderingMode(.alwaysTemplate)
        searchIconView.tintColor = searchIconColor
        searchIconView.contentMode = .scaleAspectFit
        searchIconView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(searchIconView)
        
        // 设置清除按钮
        clearButton.setImage(UIImage(named: "close_round")?.withRenderingMode(.alwaysTemplate), for: .normal)
        clearButton.tintColor = clearButtonColor
        clearButton.addTarget(self, action: #selector(clearButtonTapped), for: .touchUpInside)
        clearButton.translatesAutoresizingMaskIntoConstraints = false
        clearButton.isHidden = true // 初始时隐藏
        addSubview(clearButton)
        
        // 设置文本输入框
        textField.delegate = self
        textField.placeholder = placeholder
        textField.textColor = textColor
        textField.returnKeyType = .search
        textField.autocorrectionType = .no
        textField.autocapitalizationType = .none
        textField.clearButtonMode = .never // 使用自定义清除按钮
        textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
        textField.translatesAutoresizingMaskIntoConstraints = false
        addSubview(textField)
        
        // 设置约束
        setupConstraints()
    }
    
    private func setupConstraints() {
        NSLayoutConstraint.activate([
            // 搜索图标约束
            searchIconView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12),
            searchIconView.centerYAnchor.constraint(equalTo: centerYAnchor),
            searchIconView.widthAnchor.constraint(equalToConstant: 20),
            searchIconView.heightAnchor.constraint(equalToConstant: 20),
            
            // 清除按钮约束
            clearButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12),
            clearButton.centerYAnchor.constraint(equalTo: centerYAnchor),
            clearButton.widthAnchor.constraint(equalToConstant: 20),
            clearButton.heightAnchor.constraint(equalToConstant: 20),
            
            // 文本输入框约束
            textField.leadingAnchor.constraint(equalTo: searchIconView.trailingAnchor, constant: 8),
            textField.trailingAnchor.constraint(equalTo: clearButton.leadingAnchor, constant: -8),
            textField.topAnchor.constraint(equalTo: topAnchor, constant: 8),
            textField.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8)
        ])
    }
    
    // MARK: - 私有方法
    @objc private func clearButtonTapped() {
        textField.text = ""
        textField.becomeFirstResponder()
        updateClearButtonVisibility()
        delegate?.searchBarClearButtonClicked(self)
    }
    
    @objc private func textFieldDidChange() {
        updateClearButtonVisibility()
        delegate?.searchBar(self, textDidChange: textField.text ?? "")
    }
    
    private func updateClearButtonVisibility() {
        clearButton.isHidden = textField.text?.isEmpty ?? true
    }
    
    // MARK: - 公共方法
    func becomeActive() {
        textField.becomeFirstResponder()
    }
    
    func resignActive() {
        textField.resignFirstResponder()
    }
}

// MARK: - UITextFieldDelegate
extension CustomSearchBar: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        delegate?.searchBarDidBeginEditing(self)
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        delegate?.searchBarDidEndEditing(self)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        delegate?.searchBarSearchButtonClicked(self)
        return true
    }
}
